import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLFunc extends Function {

	int size;
	Polynom p;

	public XMLFunc(int sizeOfGroup, String nextLine) {
		this.size=sizeOfGroup;
		this.p=xmlToPolynom(nextLine);
	}
	

	public static Polynom xmlToPolynom(String filepath){
		 try {
	   
			 File file = new File(filepath);
			 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			 DocumentBuilder db = dbf.newDocumentBuilder();
			 Document doc = db.parse(file);
			 doc.getDocumentElement().normalize();
	   	   
			 Element ele = doc.getDocumentElement();
			 String functionID = ele.getAttribute("id");
	   
			 Polynom result = new Polynom(); //will be returned.

			 NodeList nodeLst = ele.getElementsByTagName("function");
	   
			 for (int s = 0; s < nodeLst.getLength(); s++) { //go over functions
				 	Node currNode = nodeLst.item(s);
				 	Element funcElem = (Element) currNode;
				 	if(funcElem.getAttribute("id").equalsIgnoreCase(functionID)){//we have the right function
				 		NodeList monoms = funcElem.getElementsByTagName("monom");
				 		double[] realParts = new double[monoms.getLength()];
				 		double[] imParts = new double[monoms.getLength()];
				 		int[] alphaParts = new int[monoms.getLength()];
				 		for(int i=0;i<monoms.getLength(); i++){
				 			NodeList reals = funcElem.getElementsByTagName("real");
				 			realParts[i] = new Double(reals.item(i).getTextContent());
				 			NodeList ims = funcElem.getElementsByTagName("image");
				 			imParts[i] = new Double(ims.item(i).getTextContent());
				 			NodeList alphas = funcElem.getElementsByTagName("alpha");
				 			alphaParts[i] = new Integer(alphas.item(i).getTextContent());
	   
				 			result.addMonom(new Monom(realParts[i],imParts[i],alphaParts[i]));
				 		}
				 	}else{
				 		continue;
				 	}
				 	return result;
	 
			 }
	    }catch (Exception e) {
	    	e.printStackTrace();
	    }
	    
	    return null;
	 }


	@Override
	public complex function(int i) {
		return p.calcPolynom(i, size);
	}

}
